<template>
  <div class="scrape-container">
    <img src="@/assets/img/scrape.png" alt="" style="width: 100%;">
    <img src="@/assets/img/pendant.png" class="pendant" alt="">
    <div class="scrape-card" ref="scrapeCardRef">
      <canvas ref="bottomCanvas" class="bottom-canvas"></canvas>
      <canvas ref="topCanvas" class="top-canvas" @mousedown="startScraping" @mousemove="scrape" @mouseup="stopScraping"
        @touchstart="startScrapingTouch" @touchmove="scrapeTouch" @touchend="stopScraping"></canvas>

      <div v-if="!isScratching && !hasStarted && remainingAttempts > 0" class="start-button"  @click="startGame">
        <div>{{ remainingAttemptsText }}</div>
        <div class="btn" style="margin-top: 10px;">
          <img src="@/assets/img/startbtn.png" style="width: 200px;" alt="">
        </div>
      </div>
      <div class="start-button" style="top: 65%" v-if="showAgain" @click="againGame">
        <div class="btn">
          <img src="@/assets/img/again.png" style="width: 200px;" alt="">
        </div>
      </div>
    </div> 

    <div class="rules-container">
      <img src="@/assets/img/scrape_rule.png" alt="" style="width: 100%;" >
      <div class="rules">
        <h4>活动有效时间：</h4>
        <div>2025年5月27日~2025年5月31日</div>
        <h4>兑奖说明：</h4>
        <div>中奖后，可在活动首页点击"我的消费券"进行查看和使用。</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import scratchCardImage from '@/assets/img/scratch-card.png';
import scratchRsImage from '@/assets/img/scratch-rs.png';
import { userApi } from '../api';
import { showFailToast } from 'vant';

// 响应式状态
const isScratching = ref(false);
const hasStarted = ref(false);
const isRevealed = ref(false);
const lastPoint = ref(null);
const showAgain = ref(false);
const remainingAttempts = ref(0);
const remainingAttemptsText = ref('');
const currentPrize = ref(null);
const prizeMessage = ref('');
const scrapedPixels = ref(0);
const totalPixels = ref(0);
const canvasWidth = ref(300);
const canvasHeight = ref(150);

// 模板引用
const scrapeCardRef = ref(null);
const bottomCanvas = ref(null);
const topCanvas = ref(null);


// 刮开阈值
const revealThreshold = 0.4; // 刮开50%面积后显示结果

// 生命周期钩子
onMounted(() => {
  initCanvas();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

const againGame = () => {
  isScratching.value = false;
  hasStarted.value = false;
  isRevealed.value  = false;
  lastPoint.value = null;
  showAgain.value = false;
  remainingAttempts.value = 0;
  remainingAttemptsText.value = '';
  initCanvas()
}

// 方法
const handleResize = () => {
  initCanvas();
};

const initCanvas = () => {
  const uid = localStorage.getItem('uid');
  const containerWidth = window.innerWidth;
  // scrape-card 设置宽度和高度
  if (scrapeCardRef.value) {
    scrapeCardRef.value.style.width = `${containerWidth * 0.92}px`;
    scrapeCardRef.value.style.height = `${containerWidth * 0.92}px`;
  }

  const container = scrapeCardRef.value;
  if (!container) return;

  // 根据容器大小调整画布大小
  const rect = container.getBoundingClientRect();
  canvasWidth.value = containerWidth * 0.92;
  canvasHeight.value = containerWidth * 0.92;

  if (bottomCanvas.value && topCanvas.value) {
    // 设置画布大小
    bottomCanvas.value.width = canvasWidth.value;
    bottomCanvas.value.height = canvasHeight.value;
    topCanvas.value.width = canvasWidth.value;
    topCanvas.value.height = canvasHeight.value;
  }
  
  userApi.checkAttendActivity({uid}).then(res => {
    if (res.code == 0) {
      remainingAttempts.value = 3;
      remainingAttemptsText.value = res.msg;
      initCanvas2(topCanvas);
    } 
  }).catch(err => {
    console.log(err);
    remainingAttempts.value = 0;
    prizeMessage.value = err;
    currentPrize.value = err;
    drawPrize();
  })
};

const initCanvas2 = (topCanvas) => {
  // 初始化顶层画布（灰色遮罩）
    const topCtx = topCanvas.value.getContext('2d');
    // 获取窗口宽度
  // 将图片设置为背景
    const backgroundImage = new Image();
    // 使用导入的图片
    backgroundImage.src = scratchCardImage;
    backgroundImage.onload = () => {
      topCtx.drawImage(backgroundImage, 0, 0, canvasWidth.value, canvasHeight.value);

      totalPixels.value = canvasWidth.value * canvasHeight.value;
      scrapedPixels.value = 0;
    };
}

const startGame = () => {
  if (remainingAttempts.value <= 0) {
    prizeMessage.value = '您的抽奖次数已用完';
    isRevealed.value = true;
    return;
  }

  hasStarted.value = true;
  isRevealed.value = false;
  selectPrize();
};

const selectPrize = () => {
  const uid = localStorage.getItem('uid');
  userApi.startAttendActivity({uid}).then(res => {
    prizeMessage.value = res.msg;
    currentPrize.value = res.msg;
    drawPrize();
  }).catch(err => {
    console.log(err);
    prizeMessage.value = err;
    currentPrize.value = err;
    drawPrize();
  })
};

const drawPrize = () => {
  if (!bottomCanvas.value) return;
  const bottomCtx = bottomCanvas.value.getContext('2d');

  // 清空画布
  bottomCtx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);

  // 将图片设置为背景
  const backgroundImage = new Image();
  // 使用导入的图片
  backgroundImage.src = scratchRsImage;
  backgroundImage.onload = () => {
    bottomCtx.drawImage(backgroundImage, 0, 0, canvasWidth.value, canvasHeight.value);

    // 绘制奖品文字
    bottomCtx.fillStyle = '#D50000'; // 红色文字
    bottomCtx.font = 'bold 24px Arial';
    bottomCtx.textAlign = 'center';
    bottomCtx.textBaseline = 'middle';
    // 绘制奖品名称
    if (currentPrize.value) { 
      // currentPrize.value 满 10个字换行
      if (currentPrize.value.length > 11) {
        bottomCtx.fillText(currentPrize.value.substring(0, 11), canvasWidth.value / 2, canvasHeight.value / 2 - 20);
        bottomCtx.fillText(currentPrize.value.substring(11), canvasWidth.value / 2, canvasHeight.value / 2 + 20);
      } else {
        bottomCtx.fillText(currentPrize.value, canvasWidth.value / 2, canvasHeight.value / 2); 
      }
    }
  };
};

const startScraping = (event) => {
  if (!hasStarted.value) return;

  isScratching.value = true;
  if (!topCanvas.value) return;
  
  const rect = topCanvas.value.getBoundingClientRect();
  lastPoint.value = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  };
};

const startScrapingTouch = (event) => {
  if (!hasStarted.value) return;

  event.preventDefault(); // 防止页面滚动
  isScratching.value = true;
  if (!topCanvas.value) return;
  
  const rect = topCanvas.value.getBoundingClientRect();
  const touch = event.touches[0];
  lastPoint.value = {
    x: touch.clientX - rect.left,
    y: touch.clientY - rect.top
  };
};

const scrape = (event) => {
  if (!isScratching.value || !lastPoint.value || !topCanvas.value) return;

  const rect = topCanvas.value.getBoundingClientRect();
  const currentPoint = {
    x: event.clientX - rect.left,
    y: event.clientY - rect.top
  };

  drawLine(lastPoint.value, currentPoint);
  lastPoint.value = currentPoint;

  checkRevealPercentage();
};

const scrapeTouch = (event) => {
  if (!isScratching.value || !lastPoint.value || !topCanvas.value) return;

  event.preventDefault(); // 防止页面滚动
  const rect = topCanvas.value.getBoundingClientRect();
  const touch = event.touches[0];
  const currentPoint = {
    x: touch.clientX - rect.left,
    y: touch.clientY - rect.top
  };

  drawLine(lastPoint.value, currentPoint);
  lastPoint.value = currentPoint;

  checkRevealPercentage();
};

const drawLine = (start, end) => {
  if (!topCanvas.value) return;
  
  const ctx = topCanvas.value.getContext('2d');
  const radius = 15; // 刮痕半径

  ctx.globalCompositeOperation = 'destination-out';
  ctx.beginPath();

  // 绘制从上一点到当前点的线条
  ctx.moveTo(start.x, start.y);
  ctx.lineTo(end.x, end.y);
  ctx.lineWidth = radius * 2;
  ctx.lineCap = 'round';
  ctx.stroke();

  // 估算刮开的像素数量
  const distance = Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2));
  const scratchArea = distance * radius * 2;
  scrapedPixels.value += scratchArea;
};

const checkRevealPercentage = () => {
  const percentScraped = scrapedPixels.value / totalPixels.value;

  if (percentScraped > revealThreshold && !isRevealed.value) {
    revealAll();
    showAgain.value = true;
  }
};

const revealAll = () => {
  if (!topCanvas.value) return;
  
  const ctx = topCanvas.value.getContext('2d');
  ctx.clearRect(0, 0, canvasWidth.value, canvasHeight.value);
  isRevealed.value = true;
  isScratching.value = false;
  remainingAttempts.value--;
};

const stopScraping = () => {
  isScratching.value = false;
};

const resetCard = () => {
  if (remainingAttempts.value <= 0) return;

  hasStarted.value = false;
  isRevealed.value = false;
  scrapedPixels.value = 0;
  initCanvas();
};
</script>

<style scoped>
.scrape-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #E8F5E9;
  min-height: 100vh;
  position: relative;

  .scrape-card {
    position: absolute;
    left: 4%;
    top: 10px;
    border-radius: 10px;
  }
}

.scrape-header {
  margin-bottom: 20px;
  color: #2E7D32;
}


.bottom-canvas,
.top-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.start-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: #fff;
  text-align: center;
}


.result-message {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.9);
}

.result-message h3 {
  color: #D50000;
  margin-bottom: 15px;
}

.again-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  font-weight: bold;
}

.again-button:disabled {
  background-color: #BDBDBD;
  cursor: not-allowed;
}

.rules-container{
  margin-top: -150px;
  width: 94%;
  margin-left: auto;
  margin-right: auto; 
  position: relative;
  .rules{
    position: absolute;
    top: 70px;  
    width: 60%; 
    left: 0; 
    text-align: center;
    font-size: 14px;
    color:#E7E7A6;
    margin: 0 20%;
    h4{
      margin: 0;
      margin-top: 10px;
      font-size: 14px;
    }
    div{
      margin-top: 5px;
      font-size: 14px;
    }
  }
} 

.pendant{
  position: absolute;
  top: 10px;
  left: 10px;
  width: 40px;
  z-index: 1000;
}
</style>